import './index.scss'
import { Image, Segmented, Spin, Empty } from 'antd'
import { useEffect, useRef, useState } from 'react'
import { debounce } from '@/utils'
import { Link } from 'react-router-dom'
import imageSrc from '@/assets/defaultImage.png'
import { useGetAnimeList } from '@/hook'

const AnimeCard = () => {
  const ref = useRef(null)
  const [listShow, setListShow] = useState(false)
  const [cardListStyle, setCardListStyle] = useState({})
  const [selectedOption, setSelectedOption] = useState('周一')
  const [activeIndex, setActiveIndex] = useState(0)
  const { anime, updateAnimeList, loading } = useGetAnimeList()

  const options = {
    周一: 1,
    周二: 2,
    周三: 3,
    周四: 4,
    周五: 5,
    周六: 6,
    周日: 7,
  }

  useEffect(() => {
    updateAnimeList()

    // 宽度监听
    const refDiv = ref.current
    const resizeObserverHandle = (entries) => {
      // 盒子宽度
      const boxWidth = entries[0].contentRect.width

      let repeatCount = Math.floor((boxWidth - 300) / 300) + 1
      if (boxWidth <= 768) {
        repeatCount = 2 // 移动端一行显示2张图片
      }

      setCardListStyle({ gridTemplateColumns: `repeat(${repeatCount}, 1fr)` })
      if (!listShow) {
        return setListShow(true)
      }
    }

    const myObserver = new ResizeObserver(debounce(resizeObserverHandle, 500))
    if (refDiv) {
      myObserver.observe(refDiv)
    }
    return () => {
      if (refDiv) {
        myObserver.unobserve(refDiv)
      }
    }
  }, [])

  const handleOptionChange = (option) => {
    const selectedValue = options[option]
    setSelectedOption(option)
    updateAnimeList(selectedValue)
  }

  function isNew(updateTime) {
    // 获取当前时间
    const currentTime = new Date()

    // 将时间字符串转换为Date对象
    const updateDate = new Date(updateTime)

    // 计算当前时间和updateTime之间的时间差（单位：毫秒）
    const timeDiff = currentTime - updateDate

    // 将时间差转换为小时数
    const hoursDiff = Math.floor(timeDiff / (1000 * 60 * 60))

    return hoursDiff <= 25
  }

  return (
    <div
      style={{
        backgroundColor: '#fafafa',
        padding: '0 30px 20px 30px',
        borderRadius: '10px',
      }}
      ref={ref}
    >
      {listShow && (
        <>
          <div className="anime-heading m-anime-heading animate__animated animate__zoomIn">
            <h2 className="anime-title m-anime-title">本周番剧更新</h2>
            <div className="anime-tab">
              <Segmented
                options={Object.keys(options)}
                value={selectedOption}
                onChange={(option) => handleOptionChange(option)}
              />
            </div>
          </div>
          {anime && anime.data && anime.data.length > 0 ? (
            <div className="anime-main">
              <div className="card-list" style={cardListStyle}>
                {anime.data.map((item, index) => (
                  <div
                    key={item.id}
                    className="card card-item animate__animated animate__zoomIn"
                    style={{ animationDelay: `${index * 0.1}s` }}
                  >
                    {item.total ? (
                      <Link
                        to={`/anime/play/${item.id}/${activeIndex + 1}`}
                        draggable={false}
                      >
                        <div className="card-cover">
                          <div className="card-wrapper">
                            <div className="title">
                              {item.total ? `第${item.total}集` : '待更新'}
                            </div>
                            {isNew(item.updateTime) && (
                              <div className="card-new">new</div>
                            )}
                          </div>
                          <Image
                            src={item.poster}
                            referrerPolicy="no-referrer"
                            loading="lazy"
                            fallback={imageSrc}
                            preview={false}
                          />
                        </div>
                        <div className="card-info">
                          <span>{item.fanName}</span>
                        </div>
                      </Link>
                    ) : (
                      <div
                        className="card card-item animate__animated animate__zoomIn"
                        style={{ userSelect: 'none' }}
                      >
                        <div className="card-cover">
                          <div className="card-wrapper">
                            <div className="title">
                              {item.total ? `第${item.total}集` : '待更新'}
                            </div>
                          </div>
                          <Image
                            src={item.poster}
                            referrerPolicy="no-referrer"
                            loading="lazy"
                            fallback={imageSrc}
                            preview={false}
                          />
                        </div>
                        <div className="card-info">
                          <span>{item.fanName}</span>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <Spin>
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            </Spin>
          )}
        </>
      )}
    </div>
  )
}

export default AnimeCard
